import json

from django.contrib.auth import login, authenticate, logout
from django.http import JsonResponse
from django.views import View

from users.forms import RegisterPostForm, LoginForm
from users.models import UserProfile
from utils.common import res_data


class RegisterView(View):
    """注册"""

    def post(self, request, *args, **kwargs):
        request_dict = json.loads(request.body.decode('utf-8'))
        register_post_form = RegisterPostForm(request_dict)
        if register_post_form.is_valid():
            password = register_post_form.cleaned_data["password"]
            username = register_post_form.cleaned_data["username"]
            post = request_dict.get("post")
            user = UserProfile()
            user.set_password(password)
            user.post = post
            user.username = username
            user.save()
            login(request, user)
            return JsonResponse(res_data(ret=1))
        else:
            return JsonResponse(res_data(ret=-1, msg=json.dumps(register_post_form.errors, ensure_ascii=False)))


class LoginView(View):

    def post(self, request, *args, **kwargs):
        # 表单验证
        request_dict = json.loads(request.body.decode('utf-8'))
        login_form = LoginForm(request_dict)
        if login_form.is_valid():
            username = login_form.cleaned_data["username"]
            password = login_form.cleaned_data["password"]

            user = authenticate(username=username, password=password)

            if user is not None:
                # django自带login方法，自动设置sessionid
                login(request, user)

                sessionid = request.session.session_key
                return JsonResponse(res_data(ret=1, data=sessionid))
        return JsonResponse(res_data(ret=-1, msg=str(login_form.errors)))


class LogoutView(View):
    """
    退出登录
    """

    def get(self, request, *args, **kwargs):
        logout(request)
        return JsonResponse(res_data(ret=1))
